package org.feng.navigation.adapter.controller;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.feng.navigation.client.api.GeneratorService;
import org.feng.navigation.client.dto.generator.GeneratorCustomEnumRequestDTO;
import org.feng.navigation.client.dto.generator.GeneratorCustomEnumResponseDTO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Set;

/**
 * 菌子导航下载控制器，目前提供了界面转发、文件上传、下载的功能
 *
 * @version V1.0
 * @author: fengjinsong
 * @date: 2023年02月10日 20时02分
 */
@Api(tags = "菌子导航下载控制器")
@Slf4j
@Controller
@RequestMapping("/download")
public class JunZiNavigationDownloadController {
    @Resource
    private GeneratorService generatorService;

    private static final Set<String> SUPPORTED_FILE_SUFFIX_SET = Set.of("csv");

    /**
     * 路由到下载界面
     */
    @RequestMapping("/toDownloadCustomEnum")
    public String downloadCustomEnum() {
        return "downloadCustomEnum";
    }

    @PostMapping(value = "/customEnum", consumes = "multipart/*", headers = "content-type=multipart/form-data")
    public void downloadCustomEnum(HttpServletResponse response,
                                   @RequestParam("uploadFile") MultipartFile uploadFile,
                                   @RequestParam("customEnumClassName") String customEnumClassName,
                                   @RequestParam("fullPackageName") String fullPackageName,
                                   @RequestParam("keyIndex") Integer keyIndex
    ) throws IOException {
        String originalFilename = uploadFile.getOriginalFilename();
        boolean suffixIsMatch = SUPPORTED_FILE_SUFFIX_SET.stream().allMatch(suffix -> {
            if (StrUtil.isEmpty(originalFilename)) {
                return false;
            }
            return originalFilename.endsWith(suffix);
        });

        if (!suffixIsMatch) {
            String message = "上传的文件格式不正确！";
            log.error(message);
        }
        GeneratorCustomEnumRequestDTO requestDTO = new GeneratorCustomEnumRequestDTO();
        byte[] bytes = uploadFile.getBytes();
        requestDTO.setText(new String(bytes));
        requestDTO.setCustomEnumClassName(customEnumClassName);
        requestDTO.setFullPackageName(fullPackageName);
        requestDTO.setKeyIndex(keyIndex);
        GeneratorCustomEnumResponseDTO responseDTO = generatorService.generatorCustomEnum(requestDTO);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(requestDTO.getCustomEnumClassName() + ".java", StandardCharsets.UTF_8));
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        //设置浏览器接受类型为流
        response.setContentType("application/octet-stream;charset=UTF-8");

        // 将文件写入输入流
        try (OutputStream out = new BufferedOutputStream(response.getOutputStream())) {
            byte[] result = responseDTO.getGeneratedContent().getBytes(StandardCharsets.UTF_8);
            out.write(result);
        } catch (IOException e) {
            log.error("下载文件失败", e);
        }
    }
}
